package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Notice;
import cn.wolfcode.mapper.NoticeMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.util.UserContextUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class NoticeServiceImpl implements INoticeService {

    @Autowired
    private NoticeMapper noticeMapper;


    @Override
    public void save(Notice notice) {
        notice.setStatus(false);
        notice.setCreateTime(new Date());
        notice.setCreateUser(UserContextUtil.getCurrentEmployee());
        noticeMapper.insert(notice);
        //创建公告时默认插入公告已读记录
        noticeMapper.insertRelation(notice.getId(), UserContextUtil.getCurrentEmployee().getId());
    }

    @Override
    public void delete(Long id) {
        noticeMapper.deleteRelation(id);
        noticeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Notice notice) {
        noticeMapper.updateByPrimaryKey(notice);
    }

    @Override
    public Notice get(Long id) {
        //根据公告查询已读,若未读则插入已读记录
        int count = noticeMapper.queryShowCount(id, UserContextUtil.getCurrentEmployee().getId());
        if(count <= 0) {
            //插入已读记录
            noticeMapper.saveShowEmployee(id, UserContextUtil.getCurrentEmployee().getId());
        }
        UserContextUtil.setCurrentUnReadNotices(noticeMapper.queryNoAlready(UserContextUtil.getCurrentEmployee().getId()));
        return noticeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Notice> listAll() {
        return noticeMapper.selectAll();
    }

    @Override
    public PageInfo<Notice> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize()); //对下一句sql进行自动分页
        //获取当前用户的已读公告
        List<Long> queryAlreadyList = noticeMapper.queryAlready(UserContextUtil.getCurrentEmployee().getId());
        List<Notice> notices = noticeMapper.selectForList(qo); //里面不需要自己写limit
        //遍历结果判断当前用户是否是管理员,不是管理员移除未发布公告
        for (int i = 0; i < notices.size(); i++) {
            Notice notice = notices.get(i);
            if(!notice.isStatus() && !UserContextUtil.getCurrentEmployee().isAdmin()) notices.remove(i);
        }
        //判断公告是否已读
        for (Notice notice : notices) {
            if(queryAlreadyList.contains(notice.getId())) notice.setRead(true);
        }
        return new PageInfo<Notice>(notices);
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        noticeMapper.updateStatus(id, status);
    }

    @Override
    public List<Notice> queryNoAlready() {
        //查询用户未读公告
        return noticeMapper.queryNoAlready(UserContextUtil.getCurrentEmployee().getId());
    }
}
